package org.example.system.controller;

import cn.hutool.core.util.ObjectUtil;
import org.example.common.base.util.web.AjaxResult;
import org.example.common.base.util.web.R;
import org.example.common.security.annotation.InnerAuth;
import org.example.common.security.annotation.RequiresPermissions;
import org.example.system.api.entity.LoginUser;
import org.example.system.api.model.SysUser;
import org.example.system.service.ISysUserService;
import org.example.system.service.impl.SysPermissionService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author LiJunYi
 * @since 2020-05-25
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    private final ISysUserService userService;

    private final SysPermissionService permissionService;

    public SysUserController(ISysUserService userService, SysPermissionService permissionService) {
        this.userService = userService;
        this.permissionService = permissionService;
    }

    @RequiresPermissions("sys:user:view")
    @GetMapping("list")
    public AjaxResult list()
    {
        return AjaxResult.success(userService.getList());
    }

    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> getUserInfo(@PathVariable String username)
    {
        SysUser sysUser = userService.getByUsername(username);
        if (ObjectUtil.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolesByUserId(sysUser.getId());
        // 权限集合
        Set<String> menus = permissionService.getMenuPermissionByUserId(sysUser.getId());
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUser(sysUser);
        loginUser.setRoles(roles);
        loginUser.setPermissions(menus);
        return R.ok(loginUser);
    }
}

